package 树;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xorvud/
 */
public class 填充每个节点的下一个右侧节点指针2 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };

    public Node connect(Node root) {
        if(root == null) return null;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int sz = queue.size();
            //遍历一层
            Node pre = null; //记录上一个节点
            for (int i = 0; i < sz; i++) {
                Node cur = queue.poll();
                if(pre!=null){
                    pre.next = cur; //记录上一个节点以后，连接下一个节点
                }
                pre = cur; //转到下一个节点

                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }

        return root;
    }


}
